package com.qianbei.common.utilis.img;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;

import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.net.view.MsgAlert;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

/**
 * @author Administrator
 *         整体思想：截取屏幕的截图，然后截取矩形框里面的图片
 */
public class ClipPictureActivity extends BaseActivity implements OnTouchListener,
		OnClickListener {
	ImageView srcPic;
	Button sure, cancle;
	ClipView clipview;
	// These matrices will be used to move and zoom image
	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();

	// We can be in one of these 3 states
	static final int NONE = 0;    //初始状态
	static final int DRAG = 1;    //拖拉模式
	static final int ZOOM = 2;    //放大缩小模式
	private static final String TAG = "11";
	int mode = NONE;

	// Remember some things for zooming
	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;

	int statusBarHeight = 0;
	int titleBarHeight = 0;
	private String imageUri;
	private Intent intent;
	private String userID;
	private Bitmap fianBitmap;
	//	DisplayMetrics dm;
	private int mScreentWidth, mScreentHeight;
	/**
	 * ATTENTION: This was auto-generated to implement the App Indexing API.
	 * See https://g.co/AppIndexing/AndroidStudio for more information.
	 */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comm_imgclip_activity);

		Display mDisplay = getWindowManager().getDefaultDisplay();
		mScreentWidth = mDisplay.getWidth();
		mScreentHeight = mDisplay.getHeight();

		mScreentHeight -= getStatsBar();
		srcPic = (ImageView) this.findViewById(R.id.src_pic);
		srcPic.setOnTouchListener(this);
		sure = (Button) this.findViewById(R.id.sure);
		cancle = (Button) this.findViewById(R.id.cancle);
		sure.setOnClickListener(this);
		cancle.setOnClickListener(this);

		intent = getIntent();
		imageUri = intent.getExtras().getString("data");

		Bitmap tempbBitmap = ImageTools.bitmapFromPath(imageUri, 1080 * 2, 1920 * 2);
//		userID = GlobalConfig.getInstance().userID ;
		if (tempbBitmap != null) {
			srcPic.setImageBitmap(tempbBitmap);
			float mZoom = 1.0f;
			int imgWidth = tempbBitmap.getWidth();
			int imgHeight = tempbBitmap.getHeight();

			mZoom = (float) mScreentWidth / Math.min(imgWidth, imgHeight);
			matrix.postScale(mZoom, mZoom);
			matrix.postTranslate(0, (mScreentHeight - imgHeight * mZoom) / 2);

			srcPic.setImageMatrix(matrix);
		} else {
			new MsgAlert().show("无法加载该图片，请选择其它图片。");
			finish();
		}

		// ATTENTION: This was auto-generated to implement the App Indexing API.
		// See https://g.co/AppIndexing/AndroidStudio for more information.
	}


	int getStatsBar() {
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0, sbar = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			sbar = getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
//		    loge("get status bar height fail");
			e1.printStackTrace();
		}
		Log.d("hwr", "statusBarHeight: " + sbar + "x" + x);
		return sbar;
	}


	/**
	 * 图片读取
	 *
	 * @param bytes
	 * @param opts
	 * @return
	 */
	public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	/**
	 * 读取流
	 *
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;

	}


	/**
	 * 这里实现了多点触摸放大缩小，和单点移动图片的功能，
	 */
	public boolean onTouch(View v, MotionEvent event) {
		ImageView view = (ImageView) v;
		// Handle touch events here...
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				savedMatrix.set(matrix);
				// 設置初始點位置
				start.set(event.getX(), event.getY());
				Log.d(TAG, "mode=DRAG");
				mode = DRAG;
				break;
			case MotionEvent.ACTION_POINTER_DOWN:
				oldDist = spacing(event);
				Log.d(TAG, "oldDist=" + oldDist);
				if (oldDist > 10f) {
					savedMatrix.set(matrix);
					midPoint(mid, event);
					mode = ZOOM;
					Log.d(TAG, "mode=ZOOM");
				}
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_POINTER_UP:
				mode = NONE;
				Log.d(TAG, "mode=NONE");
				break;
			case MotionEvent.ACTION_MOVE:
				if (mode == DRAG) {
					// ...
					matrix.set(savedMatrix);
					matrix.postTranslate(event.getX() - start.x, event.getY()
							- start.y);
				} else if (mode == ZOOM) {
					float newDist = spacing(event);
					Log.d(TAG, "newDist=" + newDist);
					if (newDist > 10f) {
						matrix.set(savedMatrix);
						float scale = newDist / oldDist;
						matrix.postScale(scale, scale, mid.x, mid.y);
					}
				}
				break;
		}

		view.setImageMatrix(matrix);
		return true; // indicate event was handled
	}

	/**
	 * Determine the space between the first two fingers
	 */
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return (float) Math.sqrt(x * x + y * y);
	}

	/**
	 * Calculate the mid point of the first two fingers
	 */
	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	/*点击进入预览*/
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.sure:
				fianBitmap = zoomImage(getBitmap(), 400, 400);

				String img = bitmapToBase64(fianBitmap);
//			editUserImage(userID, img);
				String imgUri = saveBitmap(fianBitmap, "headPoint");
				intent.putExtra("imgUri", imgUri);
				setResult(RESULT_OK, intent);
				finish();
//			intent.setClass(ClipPictureActivity.this, User_Info_Activity.class);
//			intent.putExtra("bitmap", bitmapByte);

				break;

			case R.id.cancle:
				setResult(RESULT_CANCELED);
				finish();
				break;
			default:
				break;
		}

	}


	/**
	 * bitmap转为base64
	 *
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {

		String result = "";
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

				baos.flush();
				baos.close();

				byte[] bitmapBytes = baos.toByteArray();
				int bitmapSize = bitmapBytes.length;
				float periodSize = 500 * 1024;
				int bytePeriod = (int) Math.ceil(bitmapSize / periodSize);
				int offset = 0;
				int len = 0;
				for (int i = 0; i < bytePeriod; i++) {
					offset = i * (int) periodSize;
					len = Math.min((int) periodSize, bitmapSize - offset);
					result += Base64.encodeToString(bitmapBytes, offset, len, Base64.NO_WRAP);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
//	public void saveMyBitmap(String bitName) throws IOException {
//        File f = new File("/sdcard/Note/" + bitName + ".png");
//        f.createNewFile();
//        FileOutputStream fOut = null;
//        try {
//                fOut = new FileOutputStream(f);
//        } catch (FileNotFoundException e) {
//                e.printStackTrace();
//        }
//        fianBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
//        try {
//                fOut.flush();
//        } catch (IOException e) {
//                e.printStackTrace();
//        }
//        try {
//                fOut.close();
//        } catch (IOException e) {
//                e.printStackTrace();
//        }
//}

	/*获取矩形区域内的截图*/
	private Bitmap getBitmap() {
		getBarHeight();
		Bitmap screenShoot = takeScreenShot();

		clipview = (ClipView) this.findViewById(R.id.clipview);
		int width = clipview.getWidth();
		int height = clipview.getHeight();
		Bitmap finalBitmap = Bitmap.createBitmap(screenShoot,
//				(width - height / 3) / 2, height / 3 + titleBarHeight + statusBarHeight, height / 3, height / 3);
				0, (height - width) / 2 + titleBarHeight + statusBarHeight, width, width);
		return finalBitmap;
	}


	private void getBarHeight() {
		// 获取状态栏高度
		Rect frame = new Rect();
		this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		statusBarHeight = frame.top;

		int contenttop = this.getWindow()
				.findViewById(Window.ID_ANDROID_CONTENT).getTop();
		// statusBarHeight是上面所求的状态栏的高度
		titleBarHeight = contenttop - statusBarHeight;

		Log.v(TAG, "statusBarHeight = " + statusBarHeight
				+ ", titleBarHeight = " + titleBarHeight);
	}

	// 获取Activity的截屏
	private Bitmap takeScreenShot() {
		View view = this.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		return view.getDrawingCache();
	}

	/**
	 * 图片压缩
	 *
	 * @param bgimage
	 * @param newWidth
	 * @param newHeight
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
								   double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	/**
	 * 保存截取的图片
	 */
	public String saveBitmap(Bitmap bm, String picName) {
		Log.d("hwr", "保存图片");
		File cache = CanmlTools.getCacheDirectory(this);
		File f = new File(cache, picName + System.currentTimeMillis() + ".jpg");
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			bm.compress(Bitmap.CompressFormat.PNG, 90, out);
			out.flush();
			out.close();
			Log.d("hwr", "已经保存");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return f.getAbsolutePath();

	}




	/**
	 * 上传头像
	 * @param flightID
	 */
//	private void editUserImage(String userID,String image) {
//		
//		
//		ServerControl sc = new ServerControl(URL_USER+"UploadFacePic", "picData",image);
////		sc.serverListener = new ServerListener() {
//		
//		// 弹出对话框
//		sc.serverListener = new ServerListener() { 
//			@Override
//			public void serverFinish(ServerResult sr) {
//				// 关闭对话框
//				if (sr.exception != null) {
//					// 异常
//					new MsgAlert().show(mContext.getString(R.string.common_toast_net_not_connect));
//					return;
//				}
//				if (sr.isContinue) {
//					new MsgAlert().show("上传成功");
//					
//					String imgUri = saveBitmap(fianBitmap, "headPoint");
//					intent.putExtra("imgUri", imgUri);
//					setResult(RESULT_OK, intent);
//					finish();
//				}
//			}
//		};
////		new ProgressDialog(mContext).startControlPost(sc, "正在上传头像...");
//		
//		new ProgressDialog(mContext).startControl(sc, "正在上传头像...");
//	}


}